<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<!-- 新 Bootstrap 核心 CSS 文件 -->
		<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
		
		<style type="text/css">
			body{
				padding-top: 50px;
			}
			div[class^=col] {
				padding: 10px
			}
			.item{
				height: 120px;
				border-radius : 4px;
				background : #eee;
				text-align: center;
			}
		</style>
	</head>
	<script src="common.js" type="text/javascript" charset="utf-8"></script>
	<script src="cookie.js" type="text/javascript" charset="utf-8"></script>
	<script>
		"use strict";
		
		onload = function(){
			
			var btns = Array.from(document.getElementsByClassName("btn"));
			btns.forEach(function(item){
				addEventHandler(item, "click", function(){
					var no = this.parentNode.children[1].children[1].innerText;
					var pname = this.parentNode.children[0].innerText;
					var price = this.parentNode.children[1].children[0].innerText;
					
					//将提取到商品信息,封装成一个对象
					var obj = {
						"no" : no,
						"pname" : pname,
						"price" : price,
						"count" : 1
					}
					
					//从cookie中获取plist
					var plist_str = getCookie("plist");
					
					var plist = null; 
					if(plist_str == null) { //判断取出的cookie内容是否为空
						plist = []; //如果为空,则表示第一次保存商品. 所以创建一个空数组
					} else { //否则,则表示已经存过商品
						plist = JSON.parse( plist_str ); //将提取出来的字符串直接还原成对象
					}
					
					//判断数组中是否存在这个商品
					var isExist = plist.some(function(item){
						var res = item.no == obj.no;
						if(res) item.count++; //如果存在,则把商品数量+1
						return res;
					})
					
					if(!isExist) {//如果不存在
						plist.push(obj); //把刚才封装的对象,存入数组当中
					} 
					
					//把数组再一次转换为字符串,存入cookie当中
					setCookie("plist", JSON.stringify(plist), 3600*24*30);
				})
			})
			
			
			
			
			
		}
	</script>
	
	<body>
		<div class="container">
			<div class="row">
				<div class="col-lg-3 col-md-6 col-sm-9 col-xs-12">
					<div class="item">
						<p class="text-center">商品1</p>
						<p>价格： $<code>56.3</code> 编号：<span>2310</span></p>
						<a class="btn btn-warning btn-sm">购买</a>
					</div>
				</div>
				<div class="col-lg-3 col-md-6 col-sm-9 col-xs-12">
					<div class="item">
						<p class="text-center">商品2</p>
						<p>价格： $<code>999</code> 编号：<span>5610</span></p>
						<a class="btn btn-warning btn-sm">购买</a>
					</div>
				</div>
				<div class="col-lg-3 col-md-6 col-sm-9 col-xs-12">
					<div class="item">
						<p class="text-center">商品3</p>
						<p>价格： $<code>156</code> 编号：<span>1306</span></p>
						<a class="btn btn-warning btn-sm">购买</a>
					</div>
				</div>
				<div class="col-lg-3 col-md-6 col-sm-9 col-xs-12">
					<div class="item">
						<p class="text-center">商品4</p>
						<p>价格： $<code>99.5</code> 编号：<span>9985</span></p>
						<a class="btn btn-warning btn-sm">购买</a>
					</div>
				</div>
			</div>
		</div>
		
	</body>
	

</html>
